import { Image, Text, View } from "@tarojs/components"
import React, { Component } from "react"
import { connect } from 'react-redux'
import { AtButton, AtNavBar } from "taro-ui"
import Taro, { getCurrentInstance } from "@tarojs/taro"
import AxMap from '../../components/axmap/Axmap'
import FooterCommon from '../..//components/common/FooterCommon'
import IndexHeader from '../../components/Header/IndexHeader'
import ScanQrCodeButton from '../../components/Buttons/ScanQrCodeButton'
import { getToken, getUser, setUser } from '../../actions/user'
import { loginWXMP, refershToken } from '../../actions/login'
import { locationUpdate } from '../../actions/location'
import { findCabinets, getCabinets } from '../../actions/cabinets'
import { setCabinetId, setLocationVisible } from '../../actions/global'
import User from '../../components/user/User'
import Shop from '../../components/shop/Shop'
import BatteryMap from '../../components/battery-map/BatteryMap'
import CarRentalMap from '../../components/car-rental-map/CarRentalMap'
import { WXRequest } from "../../utils/WXRequest"
import { URL_CREATEORDER, URL_GETCARLISTFROMSTOREID, URL_WXPAYADVANS, URL_WXPAYADVANSENCRYPT, WXAPPID } from "../../constants/SystemConstants"
import Car from '../../images/car.png'
import './Store.scss'

class Store extends Component {

  state = {
    storeId: '0',
    carList: [{"id":"浙A32345","name":"测试车辆","photo":"https://www.baidu.com/img/flexible/logo/pc/result.png","device":null},{"id":"浙A42345","name":"测试车辆","photo":"https://www.baidu.com/img/flexible/logo/pc/result.png","device":null},{"id":"浙A52345","name":"测试车辆","photo":"https://www.baidu.com/img/flexible/logo/pc/result.png","device":null},{"id":"浙A22345","name":"测试车辆","photo":"https://www.baidu.com/img/flexible/logo/pc/result.png","device":null},{"id":"浙A12345","name":"测试车辆","photo":"https://www.baidu.com/img/flexible/logo/pc/result.png","device":{"imei":"868120250240642"}}]
  }

  handleClick () {
    console.log(this.state.carList)
  }

  componentDidShow () {
    let _storeId = getCurrentInstance().router?.params.id?.toString()
    this.setState({
      storeId: _storeId
    })
    WXRequest(URL_GETCARLISTFROMSTOREID(_storeId!!), 'GET', {}).then(res => {
      this.setState({
        carList: res.data
      })
    })
  }
// 租车商品id：-5
  rentalCar (id) {
    const orderData = {
      orderItems: [
        {
          commodityId: -5,
          count: 1
        }
      ]
    }
    WXRequest(URL_CREATEORDER, 'POST', orderData).then(res => {
      WXRequest(URL_WXPAYADVANS, 'POST', { orderId: res.data.id, type: 0, appId: WXAPPID }).then(wxpayRes => {
        WXRequest(URL_WXPAYADVANSENCRYPT(wxpayRes.data.prepayId), 'POST', { appId: WXAPPID }).then(encryptRes => {
          Taro.requestPayment({
            ...encryptRes.data,
            success: () => {
              WXRequest('https://test.aixiang2018.com/api/v2/rent-scooter-logs', 'POST', 
              {
                "scooterRentalId": this.state.storeId, // number(int): 车行ID
                "scooterId": id, // string: 车牌号
                "time": { // object?: 租车时间,默认将上面的天数计入
                    "hours": 0, // number(int)?: 小时数,默认为0
                    "days": 1, // number(int)?: 天数,默认为0
                    "weeks": 0, // number(int)?: 周数,默认为0
                    "mouths": 0, // number(int)?: 月数,默认为0
                    "years": 0 // number(int)?: 年数,默认为0
                }
              }
            ).then(res => {
              console.log(res)
            }).catch(e => {
              console.error(e)
            })
            },
            fail: () => {

            }
          })
        })
      })
      console.log(res)
    }).catch(e => {
      console.error(e)
    })
  }

  render() {
    console.log(this.state.storeId)
    // const _carList = () => {
    //   this.state.carList.forEach((item, index) => {

    //   })
    // }
    return (
      <View>
        {
          this.state.carList.map((item, index) => {
            console.log(index)
            return (
              <View className='store-car-item'>
                <View className='car-img-box'>
                  <Image
                    mode='aspectFit'
                    style='width: 100%;height: 100%;'
                    src={item.photo}
                  />
                </View>
                <View className='car-detail-box'>
                  <View>
                    <Text>
                      {item.name}
                    </Text>
                  </View>
                  <View>
                    <Text>
                      {item.id}
                    </Text>
                  </View>
                </View>
                <View className='car-opt-box'>
                  <AtButton type='primary' onClick={this.rentalCar.bind(this, item.id)}>
                    立即租车
                  </AtButton>
                </View>
              </View>
            )
          })
        }
        {/* <AtNavBar
          onClickRgIconSt={this.handleClick.bind(this)}
          onClickRgIconNd={this.handleClick.bind(this)}
          onClickLeftIcon={this.handleClick.bind(this)}
          color='#000'
          title='NavBar 导航栏示例'
          leftText='返回'
          rightFirstIconType='bullet-list'
          rightSecondIconType='user'
        /> */}
      </View>
    )
  }
}



// 将 reducer 中的状态插入到组件的 props 中
// 下面是单个reducer的时候，多个的时候需要选传入哪个reducer
// const { test, count } = state
const mapStateToProps = (state) => ({
  user: state.user,
  login: state.login,
  cabinets: state.cabinets.cabinets,
  detailLogin: state.cabinets.detailLogin,
  cabinet: state.cabinets.cabinet,
  location: state.global.location
})

// 将 对应action 插入到组件的 props 中
const mapDispatchToProps = (dispatch) => ({
  getUser () {
    dispatch(getUser())
  },
  getToken () {
    dispatch(getToken())
  },
  setUser (user) {
    dispatch(setUser(user))
  },
  refershToken (token) {
    dispatch(refershToken(token))
  },
  toLogin () {
    dispatch(loginWXMP())
  },
  updateLocation() {
    dispatch(locationUpdate())
  },
  updateCabinets () {
    dispatch(findCabinets())
  },
  getCabinets (id) {
    dispatch(getCabinets(id))
  },
  setCabinetId (id) {
    dispatch(setCabinetId(id))
  },
  setLocationVisible (visible, type) {
    dispatch(setLocationVisible(visible, type))
  }
})

// 使用 connect 高阶组件对 Counter 进行包裹
export default connect(mapStateToProps, mapDispatchToProps)(Store)